{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c358f85d-1df2-4d9f-b440-1227eeb5f765",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Let's use 2 GPUs!\n",
      "Training step is done.\n"
     ]
    }
   ],
   "source": [
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "\n",
    "# 定义一个简单的模型\n",
    "class SimpleNet(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(SimpleNet, self).__init__()\n",
    "        self.fc1 = nn.Linear(10, 5000)  # 从输入特征到隐藏层的线性变换\n",
    "        self.fc2 = nn.Linear(5000, 1)   # 从隐藏层到输出的线性变换\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = torch.relu(self.fc1(x))\n",
    "        x = self.fc2(x)\n",
    "        return x\n",
    "\n",
    "# 模型实例化\n",
    "model = SimpleNet()\n",
    "\n",
    "# 如果有多个GPU可用，使用DataParallel来包装模型\n",
    "if torch.cuda.device_count() > 1:\n",
    "    print(f\"Let's use {torch.cuda.device_count()} GPUs!\")\n",
    "    model = nn.DataParallel(model)\n",
    "\n",
    "# 将模型发送到默认的设备\n",
    "model.to('cuda')\n",
    "\n",
    "# 定义损失函数和优化器\n",
    "criterion = nn.MSELoss()\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.01)\n",
    "\n",
    "# 假设的训练数据和目标\n",
    "inputs = torch.randn(640000, 10).to('cuda')  # 64个样本，每个样本10个特征\n",
    "targets = torch.randn(640000,1).to('cuda')  # 64个样本的目标值\n",
    "\n",
    "# 训练步骤\n",
    "optimizer.zero_grad()\n",
    "outputs = model(inputs)\n",
    "loss = criterion(outputs, targets)\n",
    "loss.backward()\n",
    "optimizer.step()\n",
    "\n",
    "print('Training step is done.')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
